import datetime
import math
from datetime import datetime
from google.appengine.ext import db

import datamodel
import page
from settings import Settings

class Thread():
  relid = 0
  navlinks = ''
  posts = ''
  replieshidden = 0
  op_postid = 0
  op_key = None
  posts_in_thread = 0

def getposts(self, thread_op=None,startat=0,special=None):
  threads = []
  posts = []
  
  if thread_op:
    thread_entity = datamodel.Post.get(thread_op)
    if not thread_entity:
      raise
    thread = datamodel.Post.all().ancestor(thread_entity).order('date')
    firstid = 1
    offset = 0

    if special != '':
      if special == 'l50':
        numposts = thread.count()
        offset = max(0, (numposts - 50))
        thread = thread.fetch(50, offset)
        firstid = (offset + 1)
      else:
        if special == '-100':
          thread = thread.fetch(100)
        #else:
        #  raise Exception, 'Invalid operation supplied through URL.'

    if offset > 0:
      thread_entity.relid = 1
      posts.append(thread_entity)

    # Iterate through the posts and give them their relative IDs
    i = firstid
    for post in thread:
      post.relid = i
      posts.append(post)
      i += 1

    fullthread = Thread()
    fullthread.posts = posts
    fullthread.op_postid = thread_entity.postid
    fullthread.op_key = thread_entity.key()
    
    threads.append(fullthread)
  else:
    op_posts = datamodel.Post.all().filter('parentid = ', None).order('-bumped').fetch(Settings.THREADS_SHOWN_ON_FRONT_PAGE, startat)
    #op_posts = op_posts.fetch(Settings.THREADS_SHOWN_ON_FRONT_PAGE, startat)

    thread_relid = 1
    for thread_parent in op_posts:
      fullthread = Thread()
      
      fullthread.posts_in_thread = thread_parent.posts
      
      offset = max((fullthread.posts_in_thread - Settings.REPLIES_SHOWN_ON_FRONT_PAGE), 0)
      if offset > 0:
        # Because we aren't showing all of the posts, we need to display the original post first
        thread_starting_post = datamodel.Post.all().ancestor(thread_parent).order('date').get()
        thread_starting_post.relid = 1
        posts.append(thread_starting_post)
        fullthread.op_postid = thread_starting_post.postid
        fullthread.op_key = thread_starting_post.key()
      
      thread = datamodel.Post.all().ancestor(thread_parent).order('date').fetch(Settings.REPLIES_SHOWN_ON_FRONT_PAGE, offset)
      
      # Iterate through the posts and give them their relative IDs
      i = (offset + 1)
      for post in thread:
        if i == 1:
          fullthread.op_postid = post.postid
          fullthread.op_key = post.key()
        post.relid = i
        posts.append(post)
        i += 1
        
      fullthread.posts = posts
      fullthread.relid = thread_relid
      if thread_relid == 1:
        fullthread.navlinks = '<a href="#15">&uarr;</a>&nbsp;<a href="#2">&darr;</a>'
      else:
        if thread_relid == 15:
          fullthread.navlinks = '<a href="#14">&uarr;</a>&nbsp;<a href="#1">&darr;</a>'
        else:
          fullthread.navlinks = '<a href="#' + str(thread_relid - 1) + '">&uarr;</a>&nbsp;<a href="#' + str(thread_relid + 1) + '">&darr;</a>'
          
      if fullthread.posts_in_thread > 1:
        replieshidden = ((fullthread.posts_in_thread - 1) - min(len(thread), Settings.REPLIES_SHOWN_ON_FRONT_PAGE))
        if replieshidden > 0:
          fullthread.replieshidden = replieshidden
      else:
        fullthread.replieshidden = None
      
      threads.append(fullthread)
      posts = []
      thread_relid += 1
  
  return threads

def deletePost(self, post):
  if post.parentid is None:
    posts = datamodel.Post.all().ancestor(post)
    for a_post in posts:
      if a_post.image:
        image = datamodel.Image.get(a_post.image)
        image.delete()
      a_post.delete()
  else:
    if post.image:
      image = datamodel.Image.get(post.image)
      image.delete()
    post.image = None
    post.image_hex = None
    post.deleted = True
    post.put()

  # Because we deleted a post, notify the script we have updated a thread
  page.threadupdated(self, post.key())

def postIDToKey(postid):
  post = datamodel.Post.all().filter('postid = ', int(postid)).get()
  return post.key()

def postKeyToID(key):
  post = datamodel.Post.get(key)
  return post.postid

def threadURL(key):
  return '/res/' + str(postKeyToID(key)) + '.html'

def trimThreads(self):
  posts = datamodel.Post.all().filter('parentid = ', None).order('-bumped')
  posts = posts.fetch(10, Settings.MAX_THREADS)

  for post in posts:
    deletePost(self, post)
